<template>
  <div class="purchase-order-create">
    <van-form @submit="onSubmit">
      <van-cell-group title="基本信息">
        <van-field
          v-model="form.supplierId"
          label="供应商"
          placeholder="请选择供应商"
          required
          readonly
          is-link
          @click="showSupplierPicker = true"
        />
        <van-field
          v-model="form.orderDate"
          label="订单日期"
          placeholder="请选择日期"
          required
          readonly
          is-link
          @click="showDatePicker = true"
        />
        <van-field
          v-model="form.totalAmount"
          label="总金额"
          placeholder="请输入总金额"
          type="number"
          required
        />
        <van-field
    v-model="form.createBy"
    label="创建人"
    readonly
  />
  <van-field
    v-model="form.updateBy"
    label="修改人"
    readonly
  />
      </van-cell-group>
      
      <van-cell-group title="订单明细">
        <div v-for="(item, index) in form.items" :key="index" class="order-item">
          <van-field
            v-model="item.productName"
            label="产品名称"
            placeholder="请输入产品名称"
            required
          />
          <van-field
            v-model="item.quantity"
            label="数量"
            placeholder="请输入数量"
            type="number"
            required
          />
          <van-field
            v-model="item.unitPrice"
            label="单价"
            placeholder="请输入单价"
            type="number"
            required
          />
          <van-button
            type="danger"
            size="small"
            @click="removeItem(index)"
          >
            删除
          </van-button>
        </div>
        
        <van-button
          type="primary"
          size="small"
          @click="addItem"
        >
          添加明细
        </van-button>
        
      </van-cell-group>
      
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交订单
        </van-button>
      </div>
    </van-form>
    
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        :min-date="minDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
    
    <van-popup v-model:show="showSupplierPicker" position="bottom">
      <van-picker
        :columns="supplierOptions"
        @confirm="onSupplierConfirm"
        @cancel="showSupplierPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getSupplierList } from '@/api/supplier'
import { createPurchaseOrder } from '@/api/purchaseOrder'
import { showSuccessToast, showFailToast } from 'vant'

export default {
  setup() {
    const router = useRouter()
    const form = ref({
      supplierId: '',
      name: '',
      orderDate: '',
      totalAmount: '',
      createBy: '当前用户', 
      updateBy: '当前用户', 
      createTime: Date.now(), 
      updateTime: Date.now(), 
      items: [
        { productName: '', quantity: '', unitPrice: '' }
      ]
    })
    const formatTime = (timestamp) => {
      if (!timestamp) return '-'
      return new Date(timestamp).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    const showDatePicker = ref(false)
    const showSupplierPicker = ref(false)
    const supplierOptions = ref([])
    const minDate = new Date(2020, 0, 1)
    
    onMounted(async () => {
      try {
        const { data } = await getSupplierList({ pageSize: 100 })
        supplierOptions.value = data.list.map(supplier => ({
          text: supplier.name,
          value: supplier.supplierId
        }))
      } catch (error) {
        console.error('获取供应商列表失败:', error)
      }
    })
    
    const onDateConfirm = (date) => {
      form.value.orderDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      showDatePicker.value = false
    }
    
    const onSupplierConfirm = ({ selectedOptions }) => {
      const supplier = selectedOptions[0]
      form.value.supplierId = supplier.value
      form.value.name = supplier.text
      showSupplierPicker.value = false
    }
    
    const addItem = () => {
      form.value.items.push({ productName: '', quantity: '', unitPrice: '' })
    }
    
    const removeItem = (index) => {
      if (form.value.items.length > 1) {
        form.value.items.splice(index, 1)
      } else {
        showFailToast('至少保留一个订单明细')
      }
    }
    
    const onSubmit = async () => {
      try {
        // 设置时间戳
        const now = Date.now()
        form.value.createTime = now
        form.value.updateTime = now
        
        await createPurchaseOrder(form.value)
        showSuccessToast('创建成功')
        router.push({ name: 'PurchaseOrderList' })
      } catch (error) {
        console.error('创建采购订单失败:', error)
        showFailToast('创建失败')
      }
    }
    
    return {
      form,
      formatTime,
      showDatePicker,
      showSupplierPicker,
      supplierOptions,
      minDate,
      onDateConfirm,
      onSupplierConfirm,
      addItem,
      removeItem,
      onSubmit
    }
  }
}
</script>

<style scoped>
.order-item {
  margin-bottom: 16px;
  padding: 0 16px;
  border-bottom: 1px solid #f5f5f5;
}
</style>